package com.greenphosphor.glasshouse;

import java.util.*;

public class RegionControl {

  public int[] primGraphIds;
  public String region;
  private int lastFreePrim = 0;

  public RegionControl ( String inRegion, int inPrimCount ) {
    region = inRegion;
    primGraphIds = new int[inPrimCount];
    for ( int i = 0; i < inPrimCount; i++ )
      primGraphIds[i] = 0;
  }

  public String getNextFreePrim ( int graphId, String nodeIdStr,
                                  HashMap<String, Integer> nodeMap ) {
    int numChecked = 0;
    while ( primGraphIds[lastFreePrim] != 0 && numChecked <= primGraphIds.length ) {
      lastFreePrim++;
      if ( lastFreePrim >= primGraphIds.length )
        lastFreePrim = 0;
      numChecked++;
    }
    if ( numChecked >= primGraphIds.length )
      return "full";
    primGraphIds[lastFreePrim] = graphId;
    nodeMap.put(nodeIdStr, new Integer(lastFreePrim + 1));
    return String.valueOf(lastFreePrim + 1);
  }

  public void freePrims ( int graphId ) {
    for ( int i = 0; i < primGraphIds.length; i++ ) {
      if ( primGraphIds[i] == graphId )
        primGraphIds[i] = 0;
    }
  }

  public LinkedList getPrimList ( int graphId ) {
    LinkedList ll = new LinkedList();
    for ( int i = 0; i < primGraphIds.length; i++ ) {
      if ( primGraphIds[i] == graphId )
        ll.add(new Integer(i));
    }
    return ll;
  }

  public void freePrims ( LinkedList ll, int layer ) {
    ListIterator li = ll.listIterator();
    while ( li.hasNext() ) {
      Integer iObj = (Integer)li.next();
      primGraphIds[iObj.intValue()] = 0;
    }
  }
}

